package com.bcx.wind.workflow.imp.cmd.repositorycmd.processmodule;

import com.bcx.wind.workflow.entity.WindProcessModule;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;
import com.bcx.wind.workflow.pojo.ProcessModule;
import com.bcx.wind.workflow.support.Assert;
import com.bcx.wind.workflow.support.ObjectHelper;

import java.util.List;

import static com.bcx.wind.workflow.message.ErrorCode.*;

/**
 * 更新流程定义模块
 *
 * @author zhanglei
 */
public class UpdateProcessModuleCommand implements Command<Integer> {

    /**
     * 流程定义模块
     */
    private WindProcessModule windProcessModule;

    private CommandContext commandContext;

    public UpdateProcessModuleCommand(WindProcessModule windProcessModule){
        this.windProcessModule = windProcessModule;
    }


    @Override
    public Integer executor(CommandContext context) {
        try{
            this.commandContext = context;
            return execute();
        }catch (Exception e){
            return 0;
        }
    }


    private Integer execute() {
        //校验参数
        checkVariable();
        //执行更新
        int ret =  this.commandContext.access().updateProcessModule(this.windProcessModule);
        //更新缓存数据
        ProcessModule module = this.commandContext.repositoryService()
                .selectDataWindProcessModule(windProcessModule.getSystem());
        this.commandContext.getConfiguration().changeProcessModuleCache(module);
        return ret;
    }




    private void checkVariable(){
        String id = this.windProcessModule.getId();
        Assert.notEmptyError(DATA_ERROR,id,"module","id");
        WindProcessModule nowModule = this.commandContext.access().selectProcessModuleById(id);
        Assert.notEmptyError(PROCESS_MODULE_NOT_FOUND,nowModule);

        //校验不可为空
        Assert.notEmptyError(PROCESS_MODULE_IS_NULL,this.windProcessModule);
        Assert.notEmptyError(PROCESS_MODULE_IS_NULL,windProcessModule.getModuleName());

        //校验父模块是否存在
        String parentId = windProcessModule.getParentId();
        Assert.notEmptyError(DATA_ERROR,parentId,"module","parentId");
        WindProcessModule module = this.commandContext.access().selectProcessModuleById(parentId);
        Assert.notEmptyError(PROCESS_PARENT_MODULE_NOT_FOUND,module);

        //校验名称重复
        String moduleName = this.windProcessModule.getModuleName();
        List<WindProcessModule> windProcessModuleList = this.commandContext.access()
                .selectProcessModule(moduleName,this.windProcessModule.getSystem(),parentId);
        Assert.isTrueError(PROCESS_MODULE_IS_SAME,!ObjectHelper.isEmpty(windProcessModuleList)
                && !this.windProcessModule.getId().equals(windProcessModuleList.get(0).getId()));
    }
}
